import numpy as np
import matplotlib.pyplot as plt
from sklearn import neighbors
# 生成样本数据
amplitude = 10
num_points = 100
# np.random.rand(100,1) 表示100*1的维度
X = amplitude * np.random.rand(num_points,1)-0.5*amplitude
# print(X)
# 计算目标
y = np.sinc(X).ravel()
print(y)
y+=0.2*(0.5-np.random.rand(y.size))
# 画出输入数据
x_values =np.linspace(-0.5*amplitude,0.5*amplitude,10*num_points)[:,np.newaxis]
n_neighbors = 8
knn_regressor = neighbors.KNeighborsRegressor(n_neighbors,weights='distance')
y_values = knn_regressor.fit(X,y).predict(x_values)

plt.figure()
plt.scatter(X,y,s=40,c='k',facecolors='none',label='input data')
plt.plot(x_values,y_values,linestyle='--',label='predicted values')
plt.xlim(X.min()-1,X.max()+1)
plt.ylim(y.min()-1,y.max()+1)
plt.legend()
plt.title("K nearst neighbors")
plt.show()